<template>
	<div class="component-upload-image">
		<div v-for="(item, index) in values" :key="index" class="image">
			<video v-if="video" :src="item" width="150" height="150" controls="controls" preload="preload" />
			<el-image v-else :src="item" :style="`width:150px;height:150px;`" fit="scale-down" />
			<div class="mask">
				<div class="actions">
					<span title="预览" @click.stop="onLookImage" :data-index="index">
						<i class="el-icon-zoom-in" />
					</span>
					<span v-if="isDelete" title="移除" @click.stop="onRemoveImage" :data-index="index">
						<i class="el-icon-delete" />
					</span>
				</div>
			</div>
		</div>
		<template v-if="!disabled">
			<el-upload
				v-if="values.length < Number(maxLength)"
				:action="uploadImgUrl"
				:headers="headers"
				:multiple="Number(maxLength) == 1 ? false : true"
				name="file"
				:show-file-list="false"
				:accept="video ? 'mp4' : 'image/jpeg,image/jpg,image/png'"
				:on-success="handleUploadSuccess"
				:on-error="handleUploadError"
				:before-upload="handleBeforeUpload"
				:on-exceed="handleExceed"
				list-type="picture-card"
				:file-list="fileList"
				:limit="4"
				:disabled="disabled"
				style="display: inline-block; vertical-align: top; margin-left: 10px"
			>
				<el-image>
					<template #error>
						<div class="image-slot">
							<i class="el-icon-plus" />
						</div>
					</template>
				</el-image>
			</el-upload>
		</template>

		<el-dialog v-if="video" v-model="dialogVisible" title="预览" width="800px" append-to-body>
			<video :src="lookValue" style="display: block; max-width: 100%; margin: 0 auto" controls="controls" preload="preload" />
			<!-- <img :src="lookValue" style="display: block; max-width: 100%; margin: 0 auto" /> -->
		</el-dialog>
		<el-image-viewer v-if="!video && dialogVisible" :initial-index="lookNum" @close="dialogVisible = false" :url-list="values" />
	</div>
</template>

<script lang="ts">
import { reactive, toRefs, ref } from 'vue';
import { ElMessage, ElLoading } from 'element-plus';

import { Session } from '/@/utils/storage';

type State = {
	fileList: Array<any>;
	values: Array<string>;
	dialogVisible: Boolean;
	lookValue: String;
	lookNum: Number;
	headers: {
		token: String;
		sign: String;
	};
	platform_url: String;
	yibao_url: String;
};

export default {
	name: 'yibaoImageUpload',
	props: {
		uploadImgUrl: {
			type: String,
			default: `${import.meta.env.VITE_API_URL}/admin/upload_organization_thumb`,
		},
		modelValue: {
			type: String,
			default: '',
		},
		maxLength: {
			type: Number,
			default: 1,
		},
		video: {
			type: Boolean,
			default: false,
		},
		disabled: {
			type: Boolean,
			default: false,
		},
		isDelete: {
			type: Boolean,
			default: true,
		},
	},
	setup(props, { emit }) {
		const loadingRef = ref();
		const state: State = reactive({
			fileList: [],
			values: [],
			dialogVisible: false,
			lookValue: '',
			platform_url: '',
			yibao_url: '',
			lookNum: 0,
			// uploadImgUrl: `${import.meta.env.VITE_API_URL}/admin/photo_thumb_upload`, // 上传的图片服务器地址
			headers: {
				token: Session.get('token'),
			},
		});

		const onRemoveImage = (e: any) => {
			const { index } = e.currentTarget.dataset;
			state.values = state.values.filter((item, i) => index != i);
			state.fileList.splice(index, 1);
			emit('update:modelValue', state.values.join(','));
			emit('onDelete');
		};

		const onLookImage = (e: any) => {
			const { index } = e.currentTarget.dataset;
			state.dialogVisible = true;
			state.lookValue = state.values[index];
			state.lookNum = Number(index);
		};
		const handleUploadSuccess = (res: any, file: any, fileList: any) => {
			console.log(res,'handleUploadSuccess')
			if (state.values.length == props.maxLength) {
				ElMessage.warning(`当前限制选择 ${props.maxLength} 张图片，系统将自动过滤剩余图片`);
				return true;
			}
			if (res.msg == 'ok') {
				urlList(res, file, fileList);
			} else {
				(loadingRef.value as any)?.close();
				ElMessage.error(file.name + '上传失败!');
			}
		};

		const handleExceed = (files: any) => {
			ElMessage.warning(
				`当前限制选择 ${props.maxLength} 张图片，本次选择了 ${files.length} 张图片，共选择了 ${files.length + state.values.length} 张图片`
			);
		};

		const handleBeforeUpload = (file: any) => {
			if (props.video) {
				let types = ['video/mp4'];
				const isJPG = types.includes(file.type);
				const isLt2M = file.size / 1024 / 1024 < 20;
				if (!isJPG) {
					ElMessage.warning('只能是 mp4 格式');
					return isJPG;
				}
				if (!isLt2M) {
					ElMessage.warning('上传视频大小不能超过 20M');
					return isLt2M;
				}
			} else {
				let types = ['image/jpeg', 'image/png', 'image/jpg'];
				const isJPG = types.includes(file.type);
				const isLt2M = file.size / 1024 / 1024 < 1;
				if (!isJPG) {
					ElMessage.warning('只能是 jpeg,png,jpg 格式');
					return isJPG;
				}
				if (!isLt2M) {
					ElMessage.warning('上传图片大小不能超过 1M');
					return isLt2M;
				}
			}
			(loadingRef.value as any) = ElLoading.service({
				lock: true,
				text: '上传中',
				background: 'rgba(0, 0, 0, 0.7)',
			});
		};

		const handleUploadError = () => {
			ElMessage.error('上传失败');
			(loadingRef.value as any)?.close();
		};

		const urlList = (res: any, file: any, fileList: any) => {
			console.log(res, file, fileList);
			let url: string = res.data.info.show_platform_url;
			state.platform_url = res.data.info.platform_url;
			state.yibao_url = res.data.info.yibao_url;
			// let name = url.split("/");
			let values: Array<string> = state.values;
			// let fileLists = this.fileList;
			console.log('url', url);
			values.push(url);
			// fileLists.push({
			//   uid: new Date().getTime(),
			//   name: name[name.length - 1],
			//   url,
			// });
			emit('update:modelValue', values.join(','));
			(loadingRef.value as any)?.close();
		};
		// 表单重置
		const reset = () => {
			state.values = [];
		};
		// 更新数据
		const dataLoading = () => {
			state.fileList = [];
			if (props.modelValue) {
				state.values = props.modelValue.split(',');
				// 首先将值转为数组
				const list = props.modelValue.split(',');
				// 然后将数组转为对象数组
				state.fileList = list.map((item: any, index) => {
					let name = item.split('/');
					let uid = item.uid || new Date().getTime() + index + 1;
					return { uid, name: name[name.length - 1], url: item };
				});
			}
		};
		return {
			loadingRef,
			onLookImage,
			onRemoveImage,
			handleUploadSuccess,
			handleExceed,
			handleBeforeUpload,
			handleUploadError,
			reset,
			dataLoading,
			...toRefs(state),
		};
	},
};
</script>

<style scoped lang="scss">
.image {
	position: relative;
	width: 150px;
	height: 150px;
	display: inline-block;
	vertical-align: top;
	margin-left: 10px;
	border: 1px dashed #c0ccda;
	.mask {
		opacity: 0;
		position: absolute;
		top: 0;
		width: 150px;
		height: 150px;
		background-color: rgba(0, 0, 0, 0.5);
		transition: all 0.3s;
		.actions {
			width: 100%;
			height: 100%;
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: space-around;
			.el-icon-zoom-in,
			.el-icon-delete {
				font-size: 20px;
				color: #fff;
			}
		}
	}
	&:hover .mask {
		opacity: 1;
	}
}
</style>
